package com.community.comsys.controller;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.community.common.entity.Building;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.community.common.annotation.Log;
import com.community.common.core.controller.BaseController;
import com.community.common.core.domain.AjaxResult;
import com.community.common.enums.BusinessType;
import com.community.comsys.service.IBuildingService;
import com.community.common.utils.poi.ExcelUtil;
import com.community.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import com.community.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 楼宇管理Controller
 * 
 * @author 潇东
 * @date 2025-10-27
 */
@RestController
@RequestMapping("/comsys/building")
public class BuildingController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(BuildingController.class);
    
    @Autowired
    private IBuildingService buildingService;
    
    @Autowired
    private RedisCache redisCache;
    
    // 缓存键前缀
    private static final String CACHE_KEY_PREFIX = "comsys:building:";
    // 缓存过期时间（分钟）
    private static final int CACHE_TIMEOUT = 30;

    /**
     * 查询楼宇管理列表
     */
    @PreAuthorize("@ss.hasPermi('comsys:building:list')")
    @GetMapping("/list")
    public TableDataInfo list(Building building)
    {
        // 生成缓存键，包含查询参数的标识
        String cacheKey = generateCacheKey("list", building);
        log.info("生成的缓存key: {}", cacheKey);
        
        // 尝试从缓存获取
        TableDataInfo cachedResult = redisCache.getCacheObject(cacheKey);
        if (cachedResult != null) {
            log.info("✅ 从Redis缓存获取楼宇列表数据");
            return cachedResult;
        }
        
        // 缓存未命中，从数据库查询
        startPage();
        List<Building> list = buildingService.selectBuildingList(building);
        TableDataInfo result = getDataTable(list);
        
        // 缓存查询结果
        redisCache.setCacheObject(cacheKey, result, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("楼宇列表数据已缓存到Redis");
        
        return result;
    }
    
    /**
     * 生成缓存键
     */
    private String generateCacheKey(String operation, Object param) {
        StringBuilder key = new StringBuilder(CACHE_KEY_PREFIX);
        key.append(operation);
        
        if (param != null) {
            // 简单的缓存键生成策略，可以根据实际需求调整
            key.append(":").append(param.toString().hashCode());
        }
        
        return key.toString();
    }
    
    /**
     * 清除所有楼宇相关缓存
     */
    private void clearBuildingCache() {
        log.info("清除楼宇相关所有缓存");
        // 获取所有楼宇相关的缓存键并删除
        redisCache.deleteObject(redisCache.keys(CACHE_KEY_PREFIX + "*"));
    }

    /**
     * 导出楼宇管理列表
     */
    @PreAuthorize("@ss.hasPermi('comsys:building:export')")
    @Log(title = "楼宇管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Building building)
    {
        List<Building> list = buildingService.selectBuildingList(building);
        ExcelUtil<Building> util = new ExcelUtil<Building>(Building.class);
        util.exportExcel(response, list, "楼宇管理数据");
    }

    /**
     * 导入楼宇列表
     * @param file
     * @return
     */
    @PreAuthorize("@ss.hasPermi('comsys:building:import')")
    @Log(title = "楼宇管理", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importData(@RequestParam("file") MultipartFile file){
        try {
            ExcelUtil<Building> util = new ExcelUtil<>(Building.class);
            List<Building> buildingList = util.importExcel(file.getInputStream());
            int result = buildingService.insertBuildingList(buildingList);
            
            if (result > 0) {
                // 导入成功，清除所有缓存
                clearBuildingCache();
            }
            
            return success(result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取楼宇管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('comsys:building:query')")
    @GetMapping(value = "/{buildingId}")
    public AjaxResult getInfo(@PathVariable("buildingId") Long buildingId)
    {
        String cacheKey = CACHE_KEY_PREFIX + "info:" + buildingId;
        
        // 尝试从缓存获取
        Building cachedBuilding = redisCache.getCacheObject(cacheKey);
        if (cachedBuilding != null) {
            log.info("✅ 从Redis缓存获取楼宇详情数据，ID: {}", buildingId);
            return success(cachedBuilding);
        }
        
        // 缓存未命中，从数据库查询
        Building building = buildingService.selectBuildingByBuildingId(buildingId);
        
        // 缓存查询结果
        if (building != null) {
            redisCache.setCacheObject(cacheKey, building, CACHE_TIMEOUT, TimeUnit.MINUTES);
            log.info("楼宇详情数据已缓存到Redis，ID: {}", buildingId);
        }
        
        return success(building);
    }

    /**
     * 新增楼宇管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:building:add')")
    @Log(title = "楼宇管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Building building)
    {
        int result = buildingService.insertBuilding(building);
        if (result > 0) {
            // 新增成功，清除所有缓存
            clearBuildingCache();
        }
        return toAjax(result);
    }

    /**
     * 修改楼宇管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:building:edit')")
    @Log(title = "楼宇管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Building building)
    {
        int result = buildingService.updateBuilding(building);
        if (result > 0) {
            // 检查是否修改了楼宇名称
            if (building.getName() != null) {
                log.info("楼宇名称已修改，需要清除相关关联缓存");
                
                // 清除楼宇相关缓存
                clearBuildingCache();
                
                // 清除关联的房屋缓存
                redisCache.deleteObject(redisCache.keys("comsys:house:*"));
                log.info("已清除所有房屋相关缓存");
                
                // 清除关联的储物间缓存
                redisCache.deleteObject(redisCache.keys("comsys:storage:room:*"));
                log.info("已清除所有储物间相关缓存");
            } else {
                // 没有修改名称，只清除楼宇相关缓存
                clearBuildingCache();
            }
            
            // 也可以只清除特定楼宇的缓存
            if (building.getBuildingId() != null) {
                String specificCacheKey = CACHE_KEY_PREFIX + "info:" + building.getBuildingId();
                redisCache.deleteObject(specificCacheKey);
                log.info("已清除特定楼宇缓存，ID: {}", building.getBuildingId());
            }
        }
        return toAjax(result);
    }

    /**
     * 删除楼宇管理
     */
    @PreAuthorize("@ss.hasPermi('comsys:building:remove')")
    @Log(title = "楼宇管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{buildingIds}")
    public AjaxResult remove(@PathVariable Long[] buildingIds)
    {
        int result = buildingService.deleteBuildingByBuildingIds(buildingIds);
        if (result > 0) {
            // 删除成功，清除所有缓存
            clearBuildingCache();
            
            // 也可以清除特定楼宇的缓存
            for (Long buildingId : buildingIds) {
                String specificCacheKey = CACHE_KEY_PREFIX + "info:" + buildingId;
                redisCache.deleteObject(specificCacheKey);
                log.info("已清除特定楼宇缓存，ID: {}", buildingId);
            }
        }
        return toAjax(result);
    }
}
